package com.xsoft.demo7;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;

public class DataBaseHelper extends SQLiteOpenHelper {

    public DataBaseHelper(@Nullable Context context) {
        this(context, "goods_db", null, 1);
    }

    public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String sql = "create table goods(id integer primary key autoincrement," +
                "name text," +
                "detail text," +
                "pictureAlbum text," +
                "picture text," +
                "price float)";
        db.execSQL(sql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    public void insert(GoodsInfo info) {
        SQLiteDatabase database = getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("name", info.getName());
        values.put("detail", info.getDetail());
        values.put("pictureAlbum", info.getPictureAlbum());
        values.put("picture", info.getPicture());
        values.put("price", info.getPrice());
        database.insert("goods", null, values);
        database.close();
    }

    public List<GoodsInfo> query() {
        List<GoodsInfo> infos = new ArrayList<>();
        SQLiteDatabase database = getWritableDatabase();
        Cursor cursor = database.query("goods", null, null, null, null, null, null);
        while (cursor.moveToNext()) {
            GoodsInfo info = new GoodsInfo();
            info.setName(cursor.getString(cursor.getColumnIndex("name")));
            info.setDetail(cursor.getString(cursor.getColumnIndex("detail")));
            info.setPictureAlbum(cursor.getString(cursor.getColumnIndex("pictureAlbum")));
            info.setPicture(cursor.getString(cursor.getColumnIndex("picture")));
            info.setPrice(cursor.getFloat(cursor.getColumnIndex("price")));
            infos.add(info);
        }
        cursor.close();
        return infos;
    }
}
